//
//  FileController.swift
//  DiZhenYuJing
//
//  Created by zhibao on 2024/8/8.
//

import UIKit
import SnapKit
import Charts
@objc class TongJiController:SuperController, AxisValueFormatter,UITableViewDelegate,UITableViewDataSource,DataChangeDelegate{
    
    var year = "2025"
    fileprivate var dataArray = [[String:Any]]()
    fileprivate var showTableView:MYTableView!
    var ciLabel = UILabel()

    var xTongJiStr = ["M≥7", "M6-M6.9", "M5-M5.9", "M4-M4.9", "M3-M3.9", "M<3"] //x轴类别项
    var tongJivalues = [10,10,10,10,10,10] //x轴对应的y轴数据
    var xMonthStr = [LocalizedString("1月"), LocalizedString("2月"), LocalizedString("3月"), LocalizedString("4月"), LocalizedString("5月"), LocalizedString("6月"), LocalizedString("7月"), LocalizedString("8月"), LocalizedString("9月"), LocalizedString("10月"), LocalizedString("11月"), LocalizedString("12月")] //x轴类别项
    var monthvalues = [10,10,10,10,10,10,10,10,10,10,10,10] //x轴对应的y轴数据
    // 柱状图
    let tongJiChartView: BarChartView = {
        $0.noDataText = LocalizedString("暂无统计数据") //无数据的时候显示
        $0.chartDescription.enabled = true //是否显示描述
        $0.scaleXEnabled = false
        $0.scaleYEnabled = false
        
        
        $0.leftAxis.drawGridLinesEnabled = false //左侧y轴设置，不画线
        $0.rightAxis.drawGridLinesEnabled = false //右侧y轴设置，不画线
        $0.rightAxis.drawAxisLineEnabled = false
        $0.rightAxis.enabled = false
        $0.legend.enabled = true
        $0.isUserInteractionEnabled = false
        
        return $0
    }(BarChartView())
    
    // 柱状图
    let monthChartView: BarChartView = {
        $0.noDataText = LocalizedString("暂无统计数据") //无数据的时候显示
        $0.chartDescription.enabled = true //是否显示描述
        $0.scaleXEnabled = false
        $0.scaleYEnabled = false
        
        
        $0.leftAxis.drawGridLinesEnabled = false //左侧y轴设置，不画线
        $0.rightAxis.drawGridLinesEnabled = false //右侧y轴设置，不画线
        $0.rightAxis.drawAxisLineEnabled = false
        $0.rightAxis.enabled = false
        $0.legend.enabled = true
        $0.isUserInteractionEnabled = false
        
        return $0
    }(BarChartView())
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.gk_navTitle = LocalizedString("地震统计")
        let calendar = Calendar.current
        let currentYear = calendar.component(.year, from: Date())
        year = "\(currentYear)"
        self.initTableView()
        self.getListData()
        self.view.backgroundColor = MYColor.color(withHexString: "f5f5f8")
        
        WYHttpHelper.sharedInstance().upload(withUrl: "alarm/statistics/count-by-year", paras: ["timeZone":"8","sortKey":"1","source":0,"pageSize":20,"year":"\(year)","pageNum":1]) { task, resposeMdoe in
            DLog(message: "resposeMode.data==\(String(describing: resposeMdoe.data))")
            let data = resposeMdoe.data as! [String:Any]
            let result = data["result"] as! [String:Any]
            let magnitudeCounts = result["magnitudeCounts"] as! [String:Int]
            self.tongJivalues.removeAll()
            let xthree = magnitudeCounts["＜3"]
            let three = magnitudeCounts["3.0-3.9"]
            let four = magnitudeCounts["4.0-4.9"]
            let five = magnitudeCounts["5.0-5.9"]
            let six = magnitudeCounts["6.0-6.9"]
            let dsix = magnitudeCounts["＞7"]
            self.tongJivalues.append(dsix ?? 0)
            self.tongJivalues.append(six ?? 0)
            self.tongJivalues.append(five ?? 0)
            self.tongJivalues.append(four ?? 0)
            self.tongJivalues.append(three ?? 0)
            self.tongJivalues.append(xthree ?? 0)
            self.setTongJiChartViewData(self.xTongJiStr, self.tongJivalues)
            let monthlyCounts = result["monthlyCounts"] as! [String:Int]
            self.monthvalues.removeAll()
            self.monthvalues.append(monthlyCounts["1"] ?? 0)
            self.monthvalues.append(monthlyCounts["2"] ?? 0)
            self.monthvalues.append(monthlyCounts["3"] ?? 0)
            self.monthvalues.append(monthlyCounts["4"] ?? 0)
            self.monthvalues.append(monthlyCounts["5"] ?? 0)
            self.monthvalues.append(monthlyCounts["6"] ?? 0)
            self.monthvalues.append(monthlyCounts["7"] ?? 0)
            self.monthvalues.append(monthlyCounts["8"] ?? 0)
            self.monthvalues.append(monthlyCounts["9"] ?? 0)
            self.monthvalues.append(monthlyCounts["10"] ?? 0)
            self.monthvalues.append(monthlyCounts["11"] ?? 0)
            self.monthvalues.append(monthlyCounts["12"] ?? 0)
            self.setMonthChartViewData(self.xMonthStr, self.monthvalues)
            let totalEarthquakes = result["totalEarthquakes"] as! Int
            self.ciLabel.text = "\(totalEarthquakes)"
            //self.initView(year: "\(currentYear)",num: totalEarthquakes)
        } failure: { task, error in
            
        }
    }
    
    func initTableView() {
        showTableView = MYTableView(frame: CGRectMake(0, navigationFullHeight(), SCREEN_WIDTH, SCREEN_HEIGHT - navigationFullHeight() - tabBarFullHeight()), style: .grouped)
        showTableView.backgroundColor = MYColor.color(withHexString: "f5f5f8")
        showTableView.delegate = self
        showTableView.dataSource = self
        showTableView.dataChangeDelegate = self
        showTableView.separatorStyle = .none
        
        let headView = self.initView(year: "\(year)",num: 0)
        showTableView.tableHeaderView = headView
        showTableView.register(TongjiCell.self, forCellReuseIdentifier: "TongjiCell")
        showTableView.register(HomeCell.self, forCellReuseIdentifier: "HomeCell")
        self.view.addSubview(showTableView)
        showTableView.noDataType = .TableViewNoDataType_FILE
        showTableView.mj_footer?.endRefreshingWithNoMoreData()
        
       
    }
    
    func initView(year:String,num:Int) -> UIView{
        let  headView = UIView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 0))
        headView.backgroundColor = MYColor.color(withHexString: "f5f5f8")
        let allView = UIView(frame: CGRect(x: pixw(p: 20), y: pixw(p: 10), width: SCREEN_WIDTH - pixw(p: 40), height: pixw(p: 80)))
        allView.backgroundColor = UIColor.white
        allView.layer.cornerRadius = pixw(p: 20)
        headView.addSubview(allView)
        let titleLabel = UILabel(frame: CGRect(x: 0, y: pixw(p: 20), width: allView.width, height: pixw(p: 20)))
        titleLabel.text = "\(year)\(LocalizedString("地震次数"))"
        titleLabel.font = MY_SCALE_SemiboldFONT(16)
        titleLabel.textAlignment = .center
        allView.addSubview(titleLabel)
        
        ciLabel.frame = CGRect(x: 0, y: titleLabel.bottom + pixw(p: 5), width: allView.width, height: pixw(p: 30))
        ciLabel.text = "\(num)"
        ciLabel.font = MY_SCALE_BoldFont(24)
        ciLabel.textAlignment = .center
        ciLabel.textColor = MYRed
        allView.addSubview(ciLabel)
        
        self.dengjiView(top: allView.bottom,headView: headView)
        return headView
    }
    
    func dengjiView(top:CGFloat,headView:UIView){
        let allView = UIView(frame: CGRect(x: pixw(p: 20), y: top + pixw(p: 10), width: SCREEN_WIDTH - pixw(p: 40), height: pixw(p: 160)))
        allView.backgroundColor = UIColor.white
        allView.layer.cornerRadius = pixw(p: 20)
        headView.addSubview(allView)
        
        let titleLabel = UILabel(frame: CGRect(x: pixw(p: 20), y: pixw(p: 10), width: allView.width - pixw(p: 40), height: pixw(p: 20)))
        titleLabel.text = LocalizedString("地震分布(等级)")
        titleLabel.font = MY_SCALE_FONT(14)
        allView.addSubview(titleLabel)
        
        tongJiChartView.frame = CGRect(x: pixw(p: 10), y: titleLabel.bottom + pixw(p: 5), width: allView.width - pixw(p: 20), height: pixw(p: 130))
        allView.addSubview(tongJiChartView)
        setTongJiChartViewData(xTongJiStr, tongJivalues)
        self.monthView(top: allView.bottom,headView: headView)
        addbulrEffectView(superView: tongJiChartView)
    }
    
    func monthView(top:CGFloat,headView:UIView){
        let allView = UIView(frame: CGRect(x: pixw(p: 20), y: top + pixw(p: 10), width: SCREEN_WIDTH - pixw(p: 40), height: pixw(p: 200)))
        allView.backgroundColor = UIColor.white
        allView.layer.cornerRadius = pixw(p: 20)
        headView.addSubview(allView)
        
        let titleLabel = UILabel(frame: CGRect(x: pixw(p: 20), y: pixw(p: 10), width: allView.width - pixw(p: 40), height: pixw(p: 20)))
        titleLabel.text = LocalizedString("地震分布(月份)")
        titleLabel.font = MY_SCALE_FONT(14)
        allView.addSubview(titleLabel)
        
        monthChartView.frame = CGRect(x: pixw(p: 10), y: titleLabel.bottom + pixw(p: 10), width: allView.width - pixw(p: 20), height: pixw(p: 160))
        allView.addSubview(monthChartView)
        setMonthChartViewData(xMonthStr, monthvalues)
        headView.height = allView.bottom + pixw(p: 20)
        addbulrEffectView(superView: monthChartView)
    }
    
    //配置柱状图
    func setTongJiChartViewData(_ dataPoints: [String], _ values: [Int]) {
        //x轴样式
        let xAxis = tongJiChartView.xAxis
        xAxis.labelPosition = .bottom //x轴的位置
        xAxis.labelFont = .systemFont(ofSize: 10)
        xAxis.drawGridLinesEnabled = false
        xAxis.granularity = 1.0
        xAxis.valueFormatter = self
        let xFormatter = IndexAxisValueFormatter()
        xFormatter.values = dataPoints

        var dataEntris: [BarChartDataEntry] = []
        for (idx, _) in dataPoints.enumerated() {
            let dataEntry = BarChartDataEntry(x: Double(idx), y: Double(values[idx]))
            dataEntris.append(dataEntry)
        }
        let chartDataSet = BarChartDataSet(entries: dataEntris, label: "")
        
        chartDataSet.colors = [MYColor.color(withHexString: "ef8c89"), MYColor.color(withHexString: "ef8c89"), MYColor.color(withHexString: "fcad26"), MYColor.color(withHexString: "fcad26"), MYColor.color(withHexString: "fcad26"), MYColor.color(withHexString: "2196f3")]
        let chartData = BarChartData(dataSet: chartDataSet)

        self.tongJiChartView.data = chartData
        self.tongJiChartView.animate(yAxisDuration: 0.4)
    }
    
    func setMonthChartViewData(_ dataPoints: [String], _ values: [Int]) {
        //x轴样式
        let xAxis = monthChartView.xAxis
        xAxis.labelPosition = .bottom //x轴的位置
        xAxis.labelFont = .systemFont(ofSize: 9)
        xAxis.drawGridLinesEnabled = false
        xAxis.granularity = 1.0
        xAxis.valueFormatter = self
        let xFormatter = IndexAxisValueFormatter()
        xFormatter.values = dataPoints

        var dataEntris: [BarChartDataEntry] = []
        for (idx, _) in dataPoints.enumerated() {
            let dataEntry = BarChartDataEntry(x: Double(idx), y: Double(values[idx]))
            dataEntris.append(dataEntry)
        }
        let chartDataSet = BarChartDataSet(entries: dataEntris, label: "")
        
        chartDataSet.colors = [MYColor.color(withHexString: "fcad26"),
                               MYColor.color(withHexString: "fcad26"),
                               MYColor.color(withHexString: "fcad26"),
                               MYColor.color(withHexString: "fcad26"),
                               MYColor.color(withHexString: "fcad26"),
                               MYColor.color(withHexString: "fcad26"),
                               MYColor.color(withHexString: "fcad26"),
                               MYColor.color(withHexString: "fcad26"),
                               MYColor.color(withHexString: "fcad26"),
                               MYColor.color(withHexString: "fcad26"),
                               MYColor.color(withHexString: "fcad26"),
                               MYColor.color(withHexString: "fcad26"),
        ]
        let chartData = BarChartData(dataSet: chartDataSet)

        self.monthChartView.data = chartData
        self.monthChartView.animate(yAxisDuration: 0.4)
    }
}

extension TongJiController{
    func stringForValue(_ value: Double, axis: Charts.AxisBase?) -> String {
        if axis?.labelFont == .systemFont(ofSize: 9) {
            return xMonthStr[Int(value) % xMonthStr.count]
        }
        return xTongJiStr[Int(value) % xTongJiStr.count]
    }
}

extension TongJiController {
    func getListData(){
        var paras = [AnyHashable : Any]()
        paras["source"] = 0
        paras["timeZone"] = "8"
        paras["pageSize"] = 20
        paras["zjMin"] = 1
        paras["pageNum"] = 1
        paras["dateEnd"] = Helper.getCurrentTimes("yyyy-MM-dd")
        paras["position"] = "\(MYGlobal.share().locationModel.lat),\(MYGlobal.share().locationModel.lon)"
        paras["zjMin"] = 10
        paras["dateStart"] = "\(year)-01-01"
        
        WYHttpHelper.sharedInstance().upload(withUrl: "alarm/getTop", paras: paras) { task, resposeMdoe in
            DLog(message: "getTop.data==\(String(describing: resposeMdoe.data))")
            let data = resposeMdoe.data as! [String:Any]
            let result = data["result"] as! [String:Any]
            let earthquakes = result["earthquakes"] as! [String:Any]
            self.dataArray = earthquakes["content"] as! [[String:Any]]
            self.showTableView.reloadData()
        } failure: { task, error in
            
        }

        
    }
    func refreshData(withTabelViewTag tableViewTag: Int) {
        self.getListData()
    }
    
    func loadMoreData(withTabelViewTag tableViewTag: Int) {
        self.getListData()
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let dic = dataArray[indexPath.row]
        if indexPath.row < 3 {
            var dic1 = [String:Any]()
            dic1["LOCATION_C"] = dic["location"]
            dic1["O_TIME"] = dic["time"]
            dic1["EPI_LON"] = dic["lon"]
            dic1["EPI_LAT"] = dic["lat"]
            dic1["EPI_DEPTH"] = dic["depth"]
            dic1["M"] = dic["mag"]
            let cell = tableView.dequeueReusableCell(withIdentifier: "HomeCell") as! HomeCell
            cell.updata(dic: dic1, index: indexPath.row)
            return cell
        }else{
            let cell = tableView.dequeueReusableCell(withIdentifier: "TongjiCell") as! TongjiCell
            cell.updata(dic: dic)
            cell.bgView.viewWithTag(blurEffectTag)?.isHidden = true
            return cell
        }
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let flag = MYGlobal.share().isVip()
        if(flag == false){
            Helper.alertShow(withTitle: LocalizedString("提示"), withContent: LocalizedString("您不是VIP会员，暂时无法使用该功能！点击去开通解锁该功能！"), withSureBtnTitle: LocalizedString("去开通"), withCancelBtnTitle: LocalizedString("取消")) { index in
                //去往购买中心
                if index == 1 {
                    let controller = PayMarkController()
                    self.navigationController?.pushViewController(controller, animated: true)
                }
            }
            return
        }
        let dic = dataArray[indexPath.row]
        let controller = MapDetailController()
        var dic1 = [String:Any]()
        dic1["LOCATION_C"] = dic["location"]
        dic1["O_TIME"] = dic["time"]
        dic1["EPI_LON"] = dic["lon"]
        dic1["EPI_LAT"] = dic["lat"]
        dic1["EPI_DEPTH"] = dic["depth"]
        dic1["M"] = dic["mag"]
        controller.dic = dic1
        self.navigationController?.pushViewController(controller, animated: true)
        
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return pixw(p: 20)
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let bgView = UIView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: pixw(p: 20)))
        let headLabel = UILabel(frame: CGRect(x: pixw(p: 15), y: 0, width: pixw(p: 300), height: pixw(p: 20)))
        headLabel.text = "\(LocalizedString("等级排名"))(Top 20)"
        bgView.addSubview(headLabel)
        headLabel.textColor = MYRed
        headLabel.font = MY_SCALE_BoldFont(16)
        
        let btn = UIButton(type: .custom)
        btn.setTitle("\(LocalizedString("查看更多")) >", for: .normal)
        btn.setTitleColor(MYColor.color(withHexString: "999999"), for: .normal)
        btn.addTarget(self, action: #selector(toMore), for: .touchUpInside)
        btn.titleLabel?.font = MY_SCALE_LightFONT(13)
        bgView.addSubview(btn)
        btn.snp.makeConstraints { make in
            make.right.equalTo(bgView).offset(pixw(p: -15))
            make.height.equalTo(bgView)
        }
        return bgView
    }
    
    @objc func toMore(){
        let flag = MYGlobal.share().isVip()
        if(flag == false){
            Helper.alertShow(withTitle: LocalizedString("提示"), withContent: LocalizedString("您不是VIP会员，暂时无法使用该功能！点击去开通解锁该功能！"), withSureBtnTitle: LocalizedString("去开通"), withCancelBtnTitle: LocalizedString("取消")) { index in
                //去往购买中心
                if index == 1 {
                    let controller = PayMarkController()
                    self.navigationController?.pushViewController(controller, animated: true)
                }
            }
            return
        }
        let controller = MoreDJController()
        self.navigationController?.pushViewController(controller, animated: true)
    }
    
}
